import { Ref, ref, watch } from "vue";

export const useBindDrag = (ele: Ref<HTMLElement | undefined>) => {
  const drag = ref<boolean>(false);
  const timer = ref<number>();
  const point = ref<[number, number] | null>(null);
  const offset = ref<[number, number] | null>(null);
  const mouseDown = () => {
    drag.value = true;
    clearTimeout(timer.value);
    timer.value = -1;
    timer.value = setTimeout(() => (drag.value = true), 1000);
  };
  const mouseMove = (event: MouseEvent) => {
    if (drag.value === false) return;
    point.value = [event.offsetX, event.offsetY];
    offset.value = [event.movementX, event.movementY];
  };
  const mouseUp = () => {
    drag.value = false;
    clearTimeout(timer.value);
    timer.value = -1;
    point.value = null;
    offset.value = null;
  };
  const bind = () => {
    if (!ele.value) return;
    const target = ele.value;
    drag.value = false;
    target.removeEventListener("mousedown", mouseDown);
    target.removeEventListener("mousemove", mouseMove);
    target.removeEventListener("mouseup", mouseUp);
    target.addEventListener("mousedown", mouseDown);
    target.addEventListener("mousemove", mouseMove);
    target.addEventListener("mouseup", mouseUp);
  };
  watch(
    () => ele.value,
    () => ele.value && bind()
  );
  return { point, offset };
};
